package cn.zhage.aimin.auth1.service;

import cn.zhage.aimin.auth1.common.WxApiUrlConstants;
import cn.zhage.aimin.auth1.pojo.Jscode2sessionResult;
import cn.zhage.aimin.auth1.properties.WXProperties;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.base.Joiner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/*
 *
 * @author 渣哥
 */
@Service
@RequiredArgsConstructor
public class WxService {

    private final RestTemplate restTemplate;
    private final WXProperties wxProperties;

    public Jscode2sessionResult wxLogin(String code) {
        Map<String, String> params = new HashMap<>(6);
        params.put("appid", wxProperties.getAppid());
        params.put("secret", wxProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String paramsStr = Joiner.on("&").withKeyValueSeparator("=").join(params);
        String url = STR."\{WxApiUrlConstants.Miniprogram.DO_LOGIN_URL}?\{paramsStr}";
        String response = restTemplate.getForObject(url, String.class);
        return JSONObject.parseObject(response, Jscode2sessionResult.class);
    }


}
